﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RenRenClient;

namespace RenRenWP
{
    public partial class Login : PhoneApplicationPage
    {
        public static OAuth oauth = new OAuth();

        public Login()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (oauth.AccessToken != null && oauth.TokenExpire > DateTime.Now)
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                wbLogin.Source = null;
                wbLogin.Navigate(new Uri(oauth.GetAuthURL()));
            }
        }

        private void wbLogin_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            pbLoading.Visibility = System.Windows.Visibility.Collapsed;
            pbLoading.IsIndeterminate = false;

            if (e.Uri.AbsoluteUri.Contains(RennURL.LoginSuccess))
            {
                wbLogin.Visibility = System.Windows.Visibility.Collapsed;
                oauth.ParseToken(e.Uri.AbsoluteUri);
                if (string.IsNullOrEmpty(oauth.AccessToken))
                {
                    MessageBox.Show("登陆失败，请重试。");
                    wbLogin.Navigate(new Uri(oauth.GetAuthURL()));
                }
                else
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            }
        }

        private void wbLogin_Navigating(object sender, NavigatingEventArgs e)
        {
            pbLoading.Visibility = System.Windows.Visibility.Visible;
            pbLoading.IsIndeterminate = true;
        }
    }
}